﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NewFormatProject.Infrastructure.Atrributes;
using NewFormatProject.Infrastructure.Dto.Responses;
using NewFormatProject.Infrastructure.Dto.Responses.Objects;
using NewFormatProject.Infrastructure.EFCore;
using NewFormatProject.Server.EFCore;
using NewFormatProject.Server.Instances.Extends.Entitys;
using NewFormatProject.Server.Interfaces;

namespace NewFormatProject.Server.Instances
{
    internal class RightIOC
    {
        public SysRightServerEF rightServerEF { get; set; }
    }
    [InjectClass]
    public class RightServer : IRightServer
    {
        private readonly RightIOC _rightIOC;
        public RightServer(DbContext dbContext)
        {
            _rightIOC = new RightIOC
            {
                rightServerEF = new SysRightServerEF(dbContext)
            };
        }
        public async Task<ResponseApiDto> Add(SysRights right)
        {
            int affectedRows = await _rightIOC.rightServerEF.Add(right);
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> Delete(SysRights right)
        {
            int affectedRows = await _rightIOC.rightServerEF.Delete(right);
            return ResponseApiDto.Create(affectedRows);
        }

        private async Task<List<ResponseSysRightsDto>> GetTreeAsync(List<SysRights> rootRights)
        {
            List<ResponseSysRightsDto> result = new List<ResponseSysRightsDto>();
            foreach (var rootRight in rootRights)
            {
                result.Add(rootRight.ToResponseDto());
            }
            foreach (var res in result)
            {
                res.children = await GetTreeAsync(await _rightIOC.rightServerEF.Query(d=>d.RParentId==res.id).ToListAsync());
            }
            return result;
        }

        public async Task<ResponseApiDto> Tree()
        {
            List<SysRights> rootRights = _rightIOC.rightServerEF.Query(d => d.RParentId == null).ToList();
            return ResponseApiDto.Success("数据已获取",await GetTreeAsync(rootRights));
        }

        public async Task<ResponseApiDto> Update(SysRights right)
        {
            int affectedRows = await _rightIOC.rightServerEF.UpdateAllProperNotNull(right);
            return ResponseApiDto.Create(affectedRows);
        }
    }
}
